import React from 'react';
import { Button, Input, Form, Popconfirm, Select, Table, message } from 'antd';
import { CheckOutlined } from '@ant-design/icons';
import { RequiredLabel } from '@/components/eai-design';
import { useState, useEffect } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { SvgIcon } from '@/components/icon';
import Modals from '@/components/modals/Modals';
import ModalsBoxContent from '@/components/modals/ModalsBoxContent';
import { Empty } from '@/components/eai-design';
import AuthModal from '@/components/auth-modal/auth-modal';
import useModal from '@/hooks/use-modal/useModal';
import { convertHeaderAuthToFormData, formatAuthData, formatAuthConfig } from '@/utils/auth';

interface BusinessEditModalProps {
  visible: boolean;
  onCancel: () => void;
  updateParams: (item?: any) => void;
  addParams: (item?: any) => void;
  onConfirm: (onItem: any) => void;
  onItem?: any;
  title: string;
  isEdit?: boolean;
  onParamsChange?: (parameters: ParamsData[]) => void;
}

interface ParamsData {
  name?: string;
  type?: string;
  description?: string;
  required?: boolean;
  in?: string;
  enum?: string[];
  format?: string;
  pattern?: string;
  maximum?: string;
  minimum?: string;
  multipleOf?: string;
  items?: {
    type?: string;
    format?: string;
  };
  minItems?: number;
  maxItems?: number;
}

const BusinessEditModal: React.FC<BusinessEditModalProps> = ({
  visible,
  onCancel,
  onConfirm,
  updateParams,
  addParams,
  onItem,
  title,
  isEdit = false,
  onParamsChange,
}) => {
  const modal = useModal('input');
  const [form] = Form.useForm();
  const [tablesValue, setTablesValue] = useState<ParamsData[]>([]);
  const [authData, setAuthData] = useState<string>('');
  const [authConfig, setAuthConfig] = useState<any>(null);
  const [headerAuth, setHeaderAuth] = useState<any>({});

  const columns = [
    {
      title: '字段名',
      dataIndex: 'name',
      key: 'name',
      render: (_: any, record: ParamsData) => (
        <span className="flex items-center gap-1">
          <SvgIcon icon="message-ic4" size="12" color="#000" />
          {record.name}
        </span>
      ),
    },
    {
      title: '字段描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '必须',
      dataIndex: 'required',
      key: 'required',
      render: (_: any, record: ParamsData) => (
        <span>{record.required ? <CheckOutlined /> : '-'}</span>
      ),
    },
    {
      title: '',
      width: '15%',
      dataIndex: 'actions',
      key: 'actions',
      render: (_: any, record: ParamsData, index: number) => (
        <div className="flex items-center">
          <Button
            type="text"
            onClick={() => {
              updateParams({
                ...record,
                index,
              });
            }}
          >
            <span className="flex items-center text-[#30343D]">
              <SvgIcon icon="setting-gray" size="20" className="mr-1" />
            </span>
          </Button>
          <Popconfirm
            placement="topLeft"
            title="你确定删除吗？"
            onConfirm={() => {
              if (record.name) {
                deleteItem(record.name);
              }
            }}
            okText="Yes"
            cancelText="No"
          >
            <Button type="text">
              <span className="flex items-center text-[#30343D]">
                <SvgIcon icon="message-ic3" size="20" className="mr-1" />
              </span>
            </Button>
          </Popconfirm>
        </div>
      ),
    },
  ];

  const deleteItem = async (name: string) => {
    setTablesValue((prev) => {
      const newTablesValue = prev.filter((item) => item.name !== name);
      onParamsChange?.(newTablesValue);
      return newTablesValue;
    });
    message.success('删除成功');
  };

  useEffect(() => {
    if (onItem) {
      form.setFieldsValue(onItem);
      setTablesValue(onItem?.parameters || []);
      if (onItem?.headerAuth) {
        setAuthData(formatAuthData(onItem?.headerAuth));
        setHeaderAuth(onItem?.headerAuth);
        setAuthConfig(onItem?.headerAuth);
      }
    }
  }, [onItem, form]);

  const handleSetting = async () => {
    modal.input.open();
  };

  const handleAuthSubmit = (value: object) => {
    setAuthConfig(value);
    setAuthData(formatAuthData(value));
    setHeaderAuth(formatAuthConfig(value));
    modal.input.close();
  };

  return (
    <Modals
      open={visible}
      onCancel={onCancel}
      width={712}
      className="model-css"
      title={title}
      onOk={async () => {
        try {
          const values = await form.validateFields();
          onConfirm({
            ...values,
            parameters: tablesValue,
            headerAuth,
          });
        } catch (errorInfo) {
          console.error('Validation failed:', errorInfo);
        }
      }}
    >
      <div
        style={{
          display: 'flex',
          flexDirection: 'column',
          margin: '0px 0px',
        }}
      >
        <Form form={form} layout="vertical" className="form-item-space">
          <Form.Item
            className="form-icon-color"
            label={<RequiredLabel>业务办理接口名称</RequiredLabel>}
            name="name"
            style={{ marginTop: '4px' }}
            rules={[{ required: true, message: '请输入业务办理接口名称' }]}
            required={false}
          >
            <Input
              style={{
                borderRadius: '6px',
                border: '1px solid #DBDBDC',
                fontSize: '14px',
                width: '100%',
                padding: '8px 12px',
              }}
              placeholder="请输入名称"
              disabled={isEdit}
            />
          </Form.Item>
          <Form.Item
            className="form-icon-color"
            label={<RequiredLabel>业务办理接口地址</RequiredLabel>}
            name="http_url"
            style={{ marginTop: '4px' }}
            rules={[{ required: true, message: '请输入业务办理接口地址' }]}
            required={false}
          >
            <Input
              style={{
                borderRadius: '6px',
                border: '1px solid #DBDBDC',
                fontSize: '14px',
                width: '100%',
                padding: '8px 12px',
              }}
              placeholder="请输入地址"
              disabled={isEdit}
            />
          </Form.Item>
          <Form.Item
            className="form-icon-color"
            label={<RequiredLabel>业务办理接口说明</RequiredLabel>}
            name="description"
            style={{ marginTop: '4px' }}
            rules={[{ required: true, message: '请输入业务办理接口说明' }]}
            required={false}
          >
            <Input.TextArea
              style={{ borderRadius: '6px', border: '1px solid #DBDBDC', fontSize: '14px' }}
              placeholder="请输入"
            />
          </Form.Item>
          <Form.Item
            className="form-icon-color"
            label={<RequiredLabel>HTTP method</RequiredLabel>}
            name="http_method"
            style={{ marginTop: '4px' }}
            rules={[{ required: true, message: '请选择' }]}
            required={false}
          >
            <Select className="w-full" placeholder="请选择">
              <option value="get">get</option>
              <option value="post">post</option>
              <option value="put">put</option>
            </Select>
          </Form.Item>
          <div className="mb-2 flex items-center justify-between">
            <div className="text-text-4">参数配置</div>
            <div>
              <Button
                type="text"
                icon={<PlusOutlined />}
                onClick={() => {
                  addParams({
                    ...form.getFieldsValue(),
                    parameters: tablesValue,
                  });
                }}
              >
                添加参数
              </Button>
            </div>
          </div>
          {tablesValue?.length === 0 ? (
            <div className="h-[94px] w-full">
              <Empty fontText="还没有参数哦~" />
            </div>
          ) : (
            <ModalsBoxContent
              className={`!mr-0 mb-4 max-h-[350px] !pr-0 ${tablesValue?.length > 0 ? 'overflow-y-auto' : ''}`}
            >
              <Table
                rowClassName="cursor-pointer api-table"
                rowKey="name"
                className="common-scrollbar"
                columns={columns}
                dataSource={tablesValue}
                pagination={false}
              />
            </ModalsBoxContent>
          )}
          <div>
            <div className="mb-4 mt-1 text-[var(--text-secondary)]">鉴权配置</div>
            <div className="flex h-11 w-full items-center justify-between rounded-md bg-[var(--fill-quinary)] px-3 text-sm font-normal text-text-5">
              <div>{authData || '无'}</div>
              <div
                className="flex cursor-pointer items-center gap-1 text-sm font-normal text-[var(--geekblue-6)]"
                onClick={() => {
                  handleSetting();
                }}
              >
                <SvgIcon icon="manage" size={16} />
                设置
              </div>
            </div>
          </div>
        </Form>
      </div>
      <AuthModal
        open={modal.input.isOpen}
        onCancel={modal.input.close}
        onSubmitOk={handleAuthSubmit}
        title="鉴权配置"
        defaultValue={convertHeaderAuthToFormData(authConfig)}
        zIndex={1001}
      />
    </Modals>
  );
};

export default BusinessEditModal;
